package org.linlinjava.litemall.admin.job;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.admin.task.ScheduledCronTaskRegistrar;
import org.linlinjava.litemall.db.domain.LitemallToken;
import org.linlinjava.litemall.db.service.LitemallTokenService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@RequiredArgsConstructor
@Component
public class WxTokenRemoveJob implements Job {

    private final LitemallTokenService litemallTokenService;
    private final ScheduledCronTaskRegistrar scheduledCronTaskRegistrar;

    /**
     * 定时清理wx、admin、web登陆token 「每天凌晨执行一次」
     */
    //@Scheduled(cron = "0 0 0 * * ?")
    public void removeToken(){
        //每天取两万个token进行筛选清除过期的
        IPage<LitemallToken> litemallTokens = litemallTokenService.page(new Page<>(1,20000),Wrappers.lambdaQuery(LitemallToken.class)
                .ne(LitemallToken::getValid, 0)
                .orderByDesc(LitemallToken::getLoginTime));
        litemallTokens.getRecords().stream().forEach(litemallToken -> {
            //判断时间是否过期
            LocalDateTime expirationTime = litemallToken.getLoginTime().plusHours(litemallToken.getValidDays());
            if(LocalDateTime.now().isAfter(expirationTime)){
                litemallTokenService.removeById(litemallToken);
            }
        });
    }


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        this.removeToken();
        scheduledCronTaskRegistrar.scheduleJobLog(jobExecutionContext);
    }
}
